
import { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import {
    NavBar, ProductCard,
    Button,
    Popup,
    Cell,
    Radio
} from 'react-vant'
import axios from 'axios';
import '../sass/Pay.scss'

function Pay() {

    const [visible, setVisible] = useState(false)
    let [addressData, setAddressData] = useState([])
    let [selectIndex, setSelectIndex] = useState(-1);
    //选择的地址数据
    let [selectAddressData, setSelectAddressData] = useState({
        phone: '',
        address: '',
        receiver: '',
        isDefault: '',
    });
    let [payProduct, setPayProduct] = useState([])
    let [payInfo,setPayInfo] = useState({
        count:0,
        total:0,
    })

    let location = useLocation();
    let navigate = useNavigate()

    //获取订单数据
    let getShopbagData = sids => {
        axios({
            method: 'get',
            url: '/commitShopcart',
            params: {
                sids: JSON.stringify(location.state.sids)
            }
        }).then(res => {
            if (res.data.code == 700) {
                return navigate('/login')
            }
            if (res.data.code == 50000) {
                res.data.result.forEach(item => {
                    payInfo.count += item.count
                    payInfo.total += item.count * item.price
                })
                setPayInfo({...payInfo})
                setPayProduct(res.data.result)
            }
        })
    }
    //获取地址
    let getAddress = () => {
        axios({
            method: 'get',
            url: '/findAddress'
        }).then(res => {
            if (res.data.code == 700) {
                return navigate('/login')
            }
            if (res.data.code == 20000) {
                res.data.result.forEach((item, index) => {
                    //默认勾选默认地址
                    item.address = `${item.province}${item.city}${item.county}${item.addressDetail}`
                    if (Boolean(item.isDefault)) {
                        setSelectIndex(index);

                        setSelectAddressData({
                            phone: item.tel,
                            address: item.address,
                            isDefault: Boolean(item.isDefault),
                            receiver: item.name
                        })
                    }

                })
                setAddressData(res.data.result)
            }
        })
    }
    //选择地址
    let selectAddress = index => {

        setSelectIndex(index);

        let currentAddressData = addressData[index];

        setSelectAddressData({
            phone: currentAddressData.tel,
            address: currentAddressData.address,
            receiver: currentAddressData.name,
            isDefault: Boolean(currentAddressData.isDefault),
        })

        setVisible(false);

    }
    //立即结算
    let pay = () => {
        axios({
            method: 'post',
            url: '/pay',
            data: {
                ...selectAddressData,
                sids: JSON.stringify(location.state.sids)
            }
        }).then(res => {
            if (res.data.code == 700) {
                return navigate('/login')
            }
            if (res.data.code == 60000) {
                navigate('/payed')
            }
        })
    }


    useEffect(() => {
        if (!location.state) {
            return navigate('/shopbag')
        }
        getAddress()
        getShopbagData()
    }, [])

    return (
        <div className="pay">
            <NavBar
                title="订单结算"
                leftText="返回"
                onClickLeft={() => navigate(-1)}
            />
            <div className="content">
                <div className="address">
                    <div className="address-title" onClick={() => { setVisible(true) }}>选择地址 ＞</div>
                    <div className="address-name">
                        <div className="name">{selectAddressData.receiver}</div>
                        <div className="tel">{selectAddressData.phone}</div>
                        {<div className={selectAddressData.isDefault==1?'isdefault':''}>{selectAddressData.isDefault==1?'默认':''}</div>}
                    </div>
                    <div className="address-content">{selectAddressData.address}</div>
                </div>
                <div className="shop-list-wrap">
                    <div className="title">订单信息</div>
                    {
                        payProduct.map((item, index) => {
                            return (
                                <ProductCard
                                key={index}
                                num={item.count}
                                price={item.price}
                                desc={<div className=''>
                                    <div>{item.enname}</div>
                                </div>}
                                title={<div className='shop-name-box'>
                                    <div className='shop-name'>{item.name}</div>
                                    <div className='shop-rule'>{item.rule}</div>
                                </div>}
                                thumb={item.small_img}
                            />
                            )
                            
                        })
                    }

                </div>
                <div className="totol-price-box">
                    <div className="count">共计 {payInfo.count} 件商品</div>
                    <div className="total-price">订单金额：¥{payInfo.total}</div>
                    <div className="circle-left"></div>
                    <div className="circle-right"></div>
                </div>
            </div>
            <Popup visible={visible} onClose={() => setVisible(false)} style={{ height: '40%' }} position='bottom' closeable>
                <div className='popup' style={{ padding: '10px' }}>
                    <div className="title">选择地址</div>
                    <div className="address-list">
                        <Radio.Group value={selectIndex} onChange={index => { selectAddress(index) }}>
                            {
                                addressData.map((item, index) => {
                                    return (
                                        <div className="address-list-item" key={index}>
                                            <Cell
                                                center
                                                title={<div className="p-text">
                                                    <div className="p-user">{item.name}</div>
                                                    <div>{item.tel}</div>
                                                    <div className={item.isDefault==1?'isdefault':''}>{item.isDefault==1?'默认':''}</div>
                                                </div>}
                                                label={<div>{item.address}</div>}
                                                icon={<Radio checked={item.isCheck} checkedColor='#ee0a24' name={index}></Radio>}
                                            />
                                        </div>
                                    )
                                })
                            }
                        </Radio.Group>
                    </div>
                    <div className="pay-btn" onClick={() => navigate('/address')}>
                        <Button type='primary' round size='large'>新增地址</Button>
                    </div>
                </div>
            </Popup>
            <div className="pay-btn">
                <Button type='primary' round size='large' onClick={() => {pay()}}>立即结算</Button>
            </div>
        </div>
    )
}
export default Pay